package com.xmqian.app.project.ui.user.activity

import android.content.Context
import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.CompoundButton
import android.widget.EditText
import android.widget.LinearLayout
import androidx.appcompat.widget.AppCompatCheckBox
import androidx.appcompat.widget.AppCompatImageView
import com.coszero.common.base.mvp.BaseMvpActivity
import com.coszero.common.config.user.UserManager
import com.coszero.ui.dialog.ToastUtils
import com.coszero.utils.utils.LogX
import com.coszero.utils.utils.ResourceUtils
import com.coszero.utils.utils.StringUtils
import com.example.xmqian.R
import com.example.xmqian.databinding.ActivityLoginBinding
import com.xmqian.app.project.event.LoginEvent
import com.xmqian.app.project.ui.main.MainActivity
import com.xmqian.app.project.ui.user.contract.LoginContract
import com.xmqian.app.project.ui.user.model.LoginModel
import com.xmqian.app.project.ui.user.presenter.LoginPresenter
import org.greenrobot.eventbus.EventBus

/**
 * Desc： 普通账号密码登录
 *
 *
 * Author： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/9/20 16:10
 */
class LoginActivity : BaseMvpActivity<LoginPresenter?>(), LoginContract.View {
    var mBtnLogin: Button? = null
    var mEtUser: EditText? = null
    var mEtPwd: EditText? = null
    var mIvTogglePwdDisplay: AppCompatCheckBox? = null
    var mLlQuikLogin: ViewGroup? = null
    var textWatcher: TextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            setLoginBtnState()
        }

        override fun afterTextChanged(s: Editable) {
        }
    }
    private var binding: ActivityLoginBinding? = null

    override fun getLayoutView(): LinearLayout {
        setShowBack(false)
        title = "密码登录"
        binding = ActivityLoginBinding.inflate(layoutInflater)
        return binding!!.root
    }

    override fun getPresenter(): LoginPresenter {
        return LoginPresenter(this)
    }

    override fun initView() {
        mEtPwd = binding!!.etPwd
        mEtUser = binding!!.etUser
        mIvTogglePwdDisplay = binding!!.ivTogglePwdDisplay
        mLlQuikLogin = binding!!.llQuikLogin
        mBtnLogin = binding!!.btnLogin
        mEtPwd!!.addTextChangedListener(textWatcher)
        mEtUser!!.addTextChangedListener(textWatcher)
        mIvTogglePwdDisplay!!.setOnCheckedChangeListener { buttonView: CompoundButton?, isChecked: Boolean ->
            if (isChecked) {
                mEtPwd!!.transformationMethod =
                    HideReturnsTransformationMethod.getInstance()
            } else {
                mEtPwd!!.transformationMethod =
                    PasswordTransformationMethod.getInstance()
            }
            mEtPwd!!.setSelection(mEtPwd!!.text.toString().length)
        }
        addQuikLogin()
        binding!!.tvRegister.setOnClickListener { v: View -> onClick(v) }
        binding!!.tvForgetPwd.setOnClickListener { v: View -> onClick(v) }
        binding!!.tvQuickLogin.setOnClickListener { v: View -> onClick(v) }
        binding!!.btnLogin.setOnClickListener { v: View -> onClick(v) }
    }

    override fun initData() {
    }

    private fun setLoginBtnState() {
        if (checkUserInput()) {
            mBtnLogin!!.isEnabled = true
        } else {
            mBtnLogin!!.isEnabled = false
        }
    }

    private fun checkUserInput(): Boolean {
        //校验账号密码
        return !StringUtils.isEmpty(mEtUser!!.text.toString()) && mEtPwd!!.length() >= 4
    }

    private fun addQuikLogin() {
        if (mLlQuikLogin != null) {
            val imageView = AppCompatImageView(mActivity)
            imageView.setImageResource(R.drawable.ic_sl_weixin)
            val layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            layoutParams.setMargins(
                ResourceUtils.getDimension(this, R.dimen.dp_45).toInt(),
                0,
                0,
                0
            )
            imageView.layoutParams = layoutParams
            imageView.setOnClickListener { v: View? ->
                //点击启动微信登录程序
                ToastUtils.showMsg("启动微信中请稍后")
            }
            mLlQuikLogin!!.addView(imageView)
        }
    }

    fun onClick(v: View) {
        if (v.id == R.id.tv_register) { // 注册
            startActivity(Intent(this, RegisterActivity::class.java))
        } else if (v.id == R.id.tv_forget_pwd) { // 忘记密码
            startActivity(Intent(this, ForgetPwdActivity::class.java))
        } else if (v.id == R.id.tv_quick_login) { // 快捷登录
            startActivity(Intent(this, QuickLoginActivity::class.java))
        } else if (v.id == R.id.btn_login) { // 登录
            val userName = mEtUser!!.text.toString()
            val password = mEtPwd!!.text.toString()
            mPresenter!!.doLogin(userName, password)
        } else {
            throw IllegalStateException("Unexpected value: " + v.id)
        }
    }

    // <editor-fold desc="请求回调" defaultstate="collapsed">
    override fun onLoginSucceed(data: LoginModel) {
        LogX.i("登录成功")
        //        ToastUtils.showLongMsg(message);
        val userManager = UserManager.getInstance()
        userManager.saveLoginData(data.userName, data.headImage, data.token)
        MainActivity.Companion.startActivity(mActivity)
        EventBus.getDefault().post(LoginEvent(true))
        finish()
    }

    override fun onRequestFailed(message: String?) {
        ToastUtils.showLongMsg(message)
    }

    override val codeSuccess: Unit
        get() {
        }

    override fun onNetworkError() {
    } //</editor-fold>

    companion object {
        /**
         * 如果顶部刚好有该页面，则使用该页面，如果没有则创建，适用于推送广播创建
         */
        fun startNewTask(context: Context) {
            val intent = Intent()
            intent.setClass(context, LoginActivity::class.java)
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        }

        /**
         * 单例开启页面，如果堆栈中有，则从底部将页面拉上次，上面的页面全部销毁
         */
        fun startTask(context: Context) {
            val intent = Intent()
            intent.setClass(context, LoginActivity::class.java)
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            context.startActivity(intent)
        }

        fun startActivity(context: Context) {
            val intent = Intent()
            intent.setClass(context, LoginActivity::class.java)
            context.startActivity(intent)
        }
    }
}
